package sfms.util;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;

public class MD5 {

    /**
     * Converts a char array to an MD5 string.
     * @param message The message to be converted
     * @return The MD5 string
     */
    public static String encrypt(char[] message) {
        String md5;

        // Convert char[] to byte[] for MessageDigest.digest() method.
        String temp = new String(message);
        byte[] bytes;
        try {
            bytes = temp.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            return null;
        }

        // Nullify temp for security reasons.
        temp = null;
        
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            // Convert md5 bytes into hexadecimal representation.
            md5 = new BigInteger(1, md.digest(bytes)).toString(16);
            md = null;
        } catch (Exception e) {
            return null;
        }

        return md5;
    }
}
